<template>
	<base-page title="编辑主页">
		<view v-if="merchantInfo" class="bg-white">
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular">头像</text>
				<view class="inline-flex item-center">
					<!-- <image class="cu-avatar round size-48 mr-8" :src="formData.logo" @click="toChooseImage"></image> -->
					<button class="m-0 p-0 transparent mr-8" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="cu-avatar round size-48" :src="formData.logo"></image>
					</button>
					<image class="size-16" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
			</view>
			<view class="h-1 bg-default"></view>
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular mr-20">策划人名称</text>
				<view class="inline-flex justify-end item-center flex-1">
					<input ref="input" :focus="editable" @blur="onBlur" type="nickname" :value="formData.businessShortName" class="flex-1 text-color-hint" style="text-align:end;" />
					<image class="size-20 flex-shrink" src="@/static/svg/icon-edit.svg" @click="chooseNickname"></image>
				</view>
			</view>
			<view class="h-1 bg-default"></view>
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular">注册手机</text>
				<text class="fs-14 text-color-hint font-normal">{{merchantInfo.mobile}}</text>
			</view>
			<view class="h-1 bg-default"></view>
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular mr-20 flex-shrink">位置信息</text>
				<view class="inline-flex justify-end item-center flex-1 w-0">
					<text class="fs-14 text-color-hint font-normal text-cut mr-8" @click="toChooseLocation">{{formData.position || '去添加'}}</text>
					<image class="size-20" src="@/pagesA/static/svg/icon-location.svg"></image>
				</view>
			</view>
			<view class="h-1 bg-default"></view>
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular">策划人介绍</text>
				<view class="inline-flex item-center">
					<text class="fs-14 text-color-hint font-normal mr-13" @click="toIntroductionEdit">去编辑</text>
					<image class="size-16" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
			</view>
			<view class="h-1 bg-default"></view>
			<view class="flex justify-between item-center pl-20 pr-14" style="height:60px;">
				<text class="text-color-regular">主页背景</text>
				<view class="inline-flex item-center">
					<uni-file-picker limit="1" :image-styles="imageStyles" v-model="bgFileList" @select="selectImg($event)" disable-preview :del-icon="false">
						<view class="upload-box flex flex-col item-center justify-center text-color-hint">
							未设置
						</view>
					</uni-file-picker>
					<image class="size-16" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
			</view>
		</view>
		<template #footer>
			<view class="m-12 radius-8 bg-primary flex center h-46 fs-16 text-white font-normal" @click="submit">
				保存修改
			</view>
		</template>
	</base-page>
</template>

<script setup>
	import uniFilePicker from '@/pagesA/uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker.vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, unref, getCurrentInstance, onUnmounted, nextTick } from 'vue'
	import { useUserStore } from '@/stores/modules/user.js'
	import { getHomePageApi, updateHomePageApi } from '@/api/business.js'
	import { getPositionApi } from '@/api/index.js'
	import { uploadFileApi, uploadProgressApi } from '@/api/common.js'
	
	const userStore = useUserStore()
	const instance = getCurrentInstance()
	
	const id = ref('')
	const merchantInfo = ref()
	let bgFileList = ref([])
	const imageStyles = ref({
		width: 75,
		height: 43,
		border: {
			color: "rgba(51, 51, 51, 0.6)",
			width: '0px',
			style: 'dashed',
			radius: '8px'
		}
	})
	const selectImg = async (e) => {
		let tempFiles = e.tempFiles[0]
		let files = e.tempFilePaths
		let result = null
		uploadProgressApi(1, {
			filePath: files[0],
			name: 'file',
			complete: (uploadFileRes) => {
				result = uploadFileRes.data && JSON.parse(uploadFileRes.data)
				if (uploadFileRes.statusCode === 200) {
					if(result.data && result.code == 200){
						let item = {
							url: result.data,
							name: tempFiles.name,
							extname: tempFiles.extname
						}
						formData.value.homeBackgroundImage = result.data
						bgFileList.value = [item]
					}else{
						uni.showToast({
							icon: 'none',
							title: result.message
						})
					}
						
				} else {
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					})
				}
			}
		},(pro) => {
			if(pro.progress){
				tempFiles.progress = pro.progress
				bgFileList.value = [tempFiles]
			}
			
		})
	}
	const getHomePage = () => {
		if (id.value) {
			getHomePageApi(id.value).then(res => {
				merchantInfo.value = res
				formData.value = { ...res }
				formData.value.businessName = formData.value.businessShortName
				if(res.homeBackgroundImage){
					bgFileList.value = [{ url: res.homeBackgroundImage }]
				}
			})
		}
	}
	
	const onChooseAvatar = (e) => {
		formData.value.logo = e.detail.avatarUrl
		uploadFile(e.detail.avatarUrl)
	}
	
	const toChooseImage = () => {
		uni.chooseMedia({
			count: 1,
			mediaType: ['image'],
			success: ({ tempFiles }) => {
				uploadFile(tempFiles[0].tempFilePath)
			}
		})
	}
	
	const uploadFile = (filePath) => {
		uni.showLoading()
		uploadFileApi(1, {
			name: 'file',
			filePath: filePath
		}).then(res => {
			uni.hideLoading()
			if (res.code === 200) {
				formData.value.logo = res.data
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
			}
		}).catch(err => uni.hideLoading())
	}
	
	const editable = ref(false)
	const input = ref(null)
	
	const chooseNickname = (e) => {
		console.log('昵称选择', e, editable.value)
		// formData.value.businessName = e
		editable.value = true
	}
	const onBlur = (e) => {
		editable.value = false
		formData.value.businessName = e.detail.value
	}
	
	// 打开地图选择位置
	const toChooseLocation = () => {
		uni.chooseLocation({
			success: (res) => {
				formData.value.position = res.address
				getPositionApi({
					latitude: res.latitude,
					longitude: res.longitude
				}).then((resp) => {
					formData.value.provinceName = resp.province
					formData.value.cityName = resp.city
					formData.value.countyName = resp.countyName
				})
			}
		})
	}
	
	const toIntroductionEdit = () => {
		uni.navigateTo({
			url: '/pagesE/edit-home/edit-home',
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', unref(merchantInfo))
			}
		})
	}
	
	const formData = ref({
		id: '',
	})
	
	const submit = async () => {
		console.log('submit', merchantInfo.value, formData.value)
		uni.showLoading()
		updateHomePageApi(unref(formData)).then(res => {
			uni.hideLoading()
			uni.showToast({
				icon: 'none', 
				title: '修改成功'
			})
			userStore.getUserInfo()
			const eventChannel = instance.ctx.getOpenerEventChannel()
			eventChannel.emit('onUpdate')
			setTimeout(() => uni.navigateBack(), 1500)
		}).catch(err => uni.hideLoading())
	}
	
	onLoad((query) => {
		id.value = query.id
		getHomePage()
		uni.$on('updateHomePage', getHomePage)
	})
	
	onUnmounted(() => {
		uni.$off('updateHomePage', getHomePage)
	})
</script>
